import {
  formatDate,
  formatDate2,
  formatDuration
} from '../../utils/date'
const app = getApp()
const domain = app.globalData.domain

// pages/tenane-edit/index.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    expireTimeVis: false,
    id: null,
    personVis: false,
    customerVis: false,
    data: {},
    isShowMore: false,
    logList: [{
      content: '1'
    }, {
      content: '1'
    }, {
      content: '1'
    }, {
      content: '1'
    }, {
      content: '1'
    }]
  },
  // 选择图片
  chooseImage: function () {
    const that = this;
    // 调用选择图片的接口
    wx.chooseMedia({
      count: 1, // 默认9，设置图片的数量
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success(res) {
        // 返回选定照片的本地文件路径列表
        const tempFilePaths = res.tempFiles;
        console.log('res', res, tempFilePaths[0])
        that.setData({
          imageUrl: tempFilePaths[0] // 设置预览图
        });
        that.uploadImage(tempFilePaths[0]?.tempFilePath)
      }
    });
  },
  // 上传图片
  uploadImage: function (imageUrl) {
    const that = this;
    wx.uploadFile({
      header: {
        Authorization: wx.getStorageSync('token')
      },
      url: `${domain}/admin-api/infra/file/upload-license`, // 这里需要替换成你的服务器接口地址
      filePath: imageUrl, // 要上传文件资源的路径
      name: 'file', // 必填，后台用来解析的文件名
      formData: {
        // 'user': 'test'
      },
      success(res) {
        const data = JSON.parse(res.data);
        // 你可以根据服务器返回的数据来处理业务逻辑，例如获取图片的URL等
        console.log('data', data);
        const licenseImg = `${domain}${data.data}`
        const newData = {
          ...that.data.data,
          licenseImg
        }
        console.log('newData', newData)
        that.setData({
          data: newData
        })
      },
      fail(error) {
        // 上传失败，处理上传失败的逻辑
        console.error(error);
      }
    });
  },
  showPicker(e) {
    this.setData({
      expireTimeVis: true
    });
  },
  hidePicker() {
    const {
      mode
    } = this.data;
    this.setData({
      [`${mode}Visible`]: false,
    });
  },
  onConfirm(e) {
    const {
      value
    } = e.detail;

    console.log('confirm', value);
    const data = {
      ...this.data.data
    }
    data.expireTime = value
    this.setData({
      data
    });

    this.hidePicker();
  },
  showMore() {
    this.setData({
      isShowMore: true
    })
  },
  onBack() {
    wx.redirectTo({
      url: '../tenant/index',
    })
  },

  closeDialog() {
    this.setData({
      personVis: false,
      customerVis: false
    })
  },

  setPersonVis(event) {
    console.log(event)
    this.setData({
      personVis: event.currentTarget.dataset.value ? true : false
    })
  },
  changePhoneAlarm(e) {
    console.log(e)
    const data = {
      ...this.data.data
    }
    data.phoneAlarm = e.detail.value ? 1 : 0
    this.setData({
      data
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log('options', options)
    this.setData({
      options
    })
    if (options.id) this.init(options.id)
    if (options.id) this.initHis(options.id)
  },
  init(id) {
    wx.request({
      url: `${domain}/admin-api/system/tenant/get?id=${id}`,
      data: {

      },
      header: {
        Authorization: wx.getStorageSync('token')
      },
      success: res => {
        if (res?.data?.code == '401') {
          wx.removeStorageSync('token')
          wx.reLaunch({
            url: '../login/login',
          })
          return;
        }
        console.log('res', res)
        const data = res?.data?.data
        if (data.expireTime) data.expireTime = formatDate2(data.expireTime)
        this.setData({
          data
        })
      }
    })
  },
  initHis(id) {
    wx.request({
      url: `${domain}/admin-api/smc/modify-his/page?id=${id}`,
      data: {

      },
      header: {
        Authorization: wx.getStorageSync('token')
      },
      success: res => {
        if (res?.data?.code == '401') {
          wx.removeStorageSync('token')
          wx.reLaunch({
            url: '../login/login',
          })
          return;
        }
        console.log('res', res)
        let logList = res?.data?.data?.list

        logList = logList.map(item => {
          if (item.createTime) item.createTime = formatDate2(item.createTime)
          if (item.targetContent) item.targetContent = JSON.parse(item.targetContent)
          console.log(item.targetContent)
          return item
        })

        this.setData({
          logList
        })
      }
    })
  },
  create() {
    wx.request({
      url: `${domain}/admin-api/system/tenant/create`,
      method: "POST",
      data: {
        ...{
          "username": "test",
          password: "test",
          "name": "租户G123",
          "contactName": "G联系人",
          "contactMobile": "13588881236",
          "contactWxNo": "333",
          "status": 0,
          "website": "",
          "packageId": 111,
          "expireTime": 1735311053000,
          "accountCount": 10,
          "sceneCount": 10,
          "phoneAlarm": 1,
          "phoneQuota": 100.2,
          "address": "重庆威海市灌云县",
          "createTime": 1727448967000
        },
        ...this.data.data,
        status: 1,
        accountCount: 10,
      },
      header: {
        Authorization: wx.getStorageSync('token')
      },
      success: res => {
        if (res?.data?.code == '401') {
          wx.removeStorageSync('token')
          wx.reLaunch({
            url: '../login/login',
          })
          return;
        }

        if (res?.data?.code == 0) {
          wx.showToast({
            title: '添加成功',
            icon: 'none'
          })
          setTimeout(() => {
            wx.redirectTo({
              url: '../tenant/index',
            })
          }, 1000)
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'none'
          })
        }
      }
    })
  },
  changeValue(e) {
    console.log(e)
    const value = e.detail.value
    console.log(e)
    const data = this.data.data;
    const {
      target
    } = e.currentTarget.dataset
    data[target] = value
    console.log('data', data, target, value)
    this.setData({
      data
    })
  },
  save() {
    console.log(111)
    const data = {
      ...this.data.data
    }

    if (data.expireTime) data.expireTime = +new Date(data.expireTime)

    wx.request({
      url: `${domain}/admin-api/system/tenant/update`,
      method: "PUT",
      data: {
        ...data,
        id: this.data.options.id
      },
      header: {
        Authorization: wx.getStorageSync('token')
      },
      success: res => {
        if (res?.data?.code == '401') {
          wx.removeStorageSync('token')
          wx.reLaunch({
            url: '../login/login',
          })
          return;
        }

        if (res?.data?.code == 0) {
          wx.showToast({
            title: '保存成功',
            icon: 'none'
          })
          setTimeout(() => {
            wx.redirectTo({
              url: '../tenant/index',
            })
          }, 1000)
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'none'
          })
        }
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})